<template>
    <div class="right-board">
    <el-tabs v-model="currentTab" class="center-tabs">
      <el-tab-pane label="配置" name="field" />
      <el-tab-pane label="数据" name="data" />
      <el-tab-pane label="交互" name="interaction" />
      <el-tab-pane label="参数" name="location" />
    </el-tabs>
    <div class="field-box">
      
      <el-scrollbar class="right-scrollbar">
        <!-- 组件属性 -->
        <el-form v-show="currentTab==='field'" size="small" label-width="90px">
          <el-collapse v-model="activeName" accordion>          
            <el-collapse-item title="图形设置" name="0">
                <el-form-item label="显示工具栏">
                    <el-switch v-model="configData.chartOption.defaultGraphOptions.allowShowMiniToolBar"  />
                </el-form-item>
                <el-form-item label="显示缩略图">
                    <el-switch v-model="configData.chartOption.defaultGraphOptions.allowShowMiniView"  />
                </el-form-item>
                <el-form-item label="显示搜索框">
                    <el-switch v-model="configData.chartOption.defaultGraphOptions.allowShowMiniNameFilter"  />
                </el-form-item>
                <el-form-item label="禁用鼠标缩放">
                    <el-switch v-model="configData.chartOption.defaultGraphOptions.disableZoom"  />
                </el-form-item>
                <el-form-item label="禁用节点拖动">
                    <el-switch v-model="configData.chartOption.defaultGraphOptions.disableDragNode"  />
                </el-form-item>
                <el-form-item label="连线方式">
                    <el-select v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultJunctionPoint" placeholder="请选择">
                        <el-option
                            v-for="item in defaultJunctionPoint"
                            :key="item.key"
                            :label="item.name"
                            :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-collapse-item>

            <el-collapse-item title="节点设置" name="1">
                <el-form-item label="节点形状">
                    <el-radio-group v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultNodeShape">
                        <el-radio :label="0">圆形</el-radio>
                        <el-radio :label="1">矩形</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="节点宽度">
                    <el-slider v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultNodeWidth" show-input/>
                </el-form-item>
                <el-form-item label="节点高度">
                    <el-slider v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultNodeHeight" show-input/>
                </el-form-item>
                <el-form-item label="节点颜色">
                    <el-color-picker v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultNodeColor" show-alpha />
                </el-form-item>
                <el-form-item label="边框宽度">
                    <el-slider v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultNodeBorderWidth" show-input/>
                </el-form-item>
                <el-form-item label="边框颜色">
                    <el-color-picker v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultNodeBorderColor" show-alpha/>
                </el-form-item>
                <el-form-item label="文本颜色">
                    <el-color-picker v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultNodeFontColor" show-alpha/>
                </el-form-item>
            </el-collapse-item>
            <el-collapse-item title="线条设置" name="2">
                <el-form-item label="线条样式">
                    <el-select v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultLineShape" placeholder="请选择">
                        <el-option
                            v-for="item in defaultLineShape"
                            :key="item.key"
                            :label="item.name"
                            :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="线条宽度">
                    <el-slider v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultLineWidth" show-input/>
                </el-form-item>
                <el-form-item label="线条颜色">
                    <el-color-picker v-model="configData.chartOption.defaultGraphOptions.layouts[0].defaultLineColor" show-alpha />
                </el-form-item>
            </el-collapse-item>

            <el-collapse-item title="动画设置" name="6">
              <el-form-item v-if="configData.chartOption.animate!==undefined" label="载入动画">
                <el-select v-model="configData.chartOption.animate" placeholder="请选择">
                  <el-option
                    v-for="item in animateOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </el-form>

        <!-- 表单属性 -->
        <el-form v-show="currentTab === 'data'" size="small" label-width="90px">
          <el-form-item v-if="" label="数据源类型">
            <el-select v-model="configData.chartOption.dataSourceType" placeholder="请选择">
                <el-option
                  v-for="item in dataSourceOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>

<Databasewebsocket v-show="configData.chartOption.dataSourceType === 'websocket'" 
          :interfaceKey="configData.chartOption.interfaceKey" @getInterfaceKey="getInterfaceKey"></Databasewebsocket>
          <el-form-item v-show="configData.chartOption.dataSourceType === 'static'" label="静态数据值" prop="desc">
            <el-input type="textarea" :rows="20" v-model="staticDataValue"  @blur.prevent="changeStaticData()"></el-input>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'url'" label="接口地址">
            <el-input type="textarea" :rows="5" placeholder="请输入接口地址" v-model="interfaceUrl" @blur.prevent="changeInterfaceUrl()">
            </el-input>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'url'" label="请求方式">
            <el-radio-group v-model="configData.chartOption.requestMethod">
              <el-radio label="GET"></el-radio>
              <el-radio label="POST"></el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'url'" label="请求参数">
            <el-input type="textarea" :rows="5" placeholder="请输入请求参数" v-model="requestParameters" @blur.prevent="changeRequestParameters()">
            </el-input>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'url'" label="刷新时间">
            <el-input-number v-model="configData.chartOption.timeout" controls-position="right"  :step="1000"></el-input-number>
          </el-form-item>
        </el-form>

        <!-- 组件位置 -->
        <el-form v-show="currentTab === 'location'" size="small" label-width="90px">
          <el-form-item label="X位置">
            <el-input-number v-model="configData.x" controls-position="right"  :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="y位置">
            <el-input-number v-model="configData.y" controls-position="right" :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="宽度">
            <el-input-number v-model="configData.width" controls-position="right" :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="高度">
            <el-input-number v-model="configData.height" controls-position="right" :step="1"></el-input-number>
          </el-form-item>
        </el-form>

        <!-- 组件交互 -->
        <!-- <el-form v-show="currentTab === 'interaction'" size="small" label-width="90px">
          <el-form-item  label="是否开启图表联动">
              <el-switch v-model="configData.chartOption.isLink" @change="isLinkChange" />
          </el-form-item>

          <el-form-item v-show="configData.chartOption.isLink===true"  label="参数名称">
            <el-input v-model="arrName" placeholder="请参数名称" @blur.prevent="changeArrName()"/>
          </el-form-item>

          <el-form-item  v-show="configData.chartOption.isLink===true" label="绑定组件">
            <el-select v-model="configData.chartOption.bindList" multiple placeholder="请选择" @change="bindCharts">
              <el-option
                  v-for="item in chartList"
                  :key="item.customId"
                  :label="item.layerName"
                  :value="item.customId">
                </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item  v-show="configData.chartOption.isLink===true" label="*参数说明">
            <div class="el-form-item__content">
              <span style="word-wrap: break-word;"><i style="color:#F00;">参数名={"legendName":"xx","seriesName":"xxx","data":xxx}</i></span>
            </div>
            <div class="el-form-item__content">
              <span >legendName:图例名称</span>
              <span style="display:block;">seriesName:系列名称</span>
              <span >data:选中值</span>
            </div>
          </el-form-item>  -->

          <!-- 下钻 -->
          <!-- <el-form-item  label="是否开启图表下钻">
              <el-switch v-model="configData.chartOption.isDrillDown" @change="isDrillDownChange"/>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.isDrillDown===true"  label="下钻后展示的图表类型">
            <el-select v-model="configData.chartOption.drillDownChartType" clearable filterable placeholder="请选择" @change="drillDownChartChange">
                <el-option
                  v-for="item in drillDownOptions"
                  :key="item.chartType"
                  :label="item.layerName"
                  :value="item.chartType">
                </el-option>
              </el-select>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.isDrillDown===true" label="弹窗背景颜色">
            <el-color-picker v-model="drillBgColor" show-alpha @change="drillDownColorChange"/>
          </el-form-item>

          <el-form-item  v-show="configData.chartOption.isDrillDown===true" label="*参数说明">
            <div class="el-form-item__content">
              <span style="word-wrap: break-word;"><i style="color:#F00;">drillParam=参数值</i></span>
            </div>
          </el-form-item> 

          <drill-down-config :drillDownDialogFlag.sync="drillDownDialogFlag" :drillDownDialogData="configData.chartOption.drillDownChartOption"/>

          
          <el-form-item v-show="configData.chartOption.isDrillDown===true"  label="">
            <el-button type="primary" @click="DrillDownClick">前去设置</el-button>
          </el-form-item> -->

          <!-- 是否开启图表远程控制 -->
        
          <!-- <el-form-item  label="是否开启图表远程控制">
                <el-switch v-model="configData.chartOption.isRemote" />
          </el-form-item>
          <Interactionwebsocket v-show="configData.chartOption.isRemote === true"
          :remote = 'configData.chartOption.remote' @getRemote="getRemote"></Interactionwebsocket>
          <el-form-item  v-show="configData.chartOption.isRemote === true" label="*参数说明">
            <div class="el-form-item__content">
              <span style="word-wrap: break-word;"><i style="color:#F00;">{"legendName":"xx","seriesName":"xxx","data":xxx}</i></span>
            </div>
            <div class="el-form-item__content">
              <span >legendName:图例名称</span>
              <span style="display:block;">seriesName:系列名称</span>
              <span >data:选中值</span>
            </div>
          </el-form-item> -->
        </el-form>

      </el-scrollbar>
    </div>

    <!-- 数据库分析配置弹出页 -->
    <el-dialog title="数据分析配置" v-if="dbVisble" :visible.sync="dbVisble" width="1000px; " append-to-body>
      
      <el-form :model="bi" ref="bi" :inline="true" label-width="68px" v-loading="loading" :rules="dbRules">
        <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="目标表">
            <el-select v-model="database.tableName" placeholder="请选择" @change="tableSelectChanged">
                  <el-option
                    v-for="item in tableOptions"
                    :key="item.table_name"
                    :label="item.table_name"
                    :value="item.table_name">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>
        </el-row>

        <el-row :gutter="15">
        <el-col :span="10">
          <el-form-item v-show="database.tableName !== ''" label="图例字段" prop="legend.field">
            <el-select v-model="bi.legend.field" placeholder="请选择" @change="legendFieldChanged">
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item v-show="bi.legend.field !== ''" label="筛选" prop="legend.filter.value">
            <el-select v-model="bi.legend.filter.value" multiple filterable placeholder="请选择">
                  <el-option
                    v-for="item in bi.legend.filter.options"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>
        </el-row>

        <el-row :gutter="15">
        <el-col :span="10">
          <el-form-item v-show="database.tableName !== ''" label="坐标字段" prop="coordinate.field">
            <el-select v-model="bi.coordinate.field" placeholder="请选择" @change="coordinateFieldChanged">
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item v-show="bi.coordinate.field !== ''" label="筛选" prop="coordinate.filter.value">
            <el-select v-model="bi.coordinate.filter.value" multiple filterable placeholder="请选择" >
                  <el-option
                    v-for="item in bi.coordinate.filter.options"
                    :key="item.id"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>

        </el-row>

        <el-row :gutter="15">
        <el-col :span="10">
          <el-form-item v-show="database.tableName !== ''" label="统计字段" prop="statistics.field">
            <el-select v-model="bi.statistics.field" placeholder="请选择">
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item v-show="bi.statistics.field !== ''" label="统计类型">
            <el-select v-model="bi.statistics.type" placeholder="请选择">
                  <el-option
                    v-for="item in statisticsTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>
        </el-row>

        <el-row v-show="database.tableName !== ''">
          <el-col :span="24">
            <el-form-item label="筛选条件" class="screen">
              <div style="height:200px; overflow:auto">
                <div v-show="database.tableName !== ''" style="display: flex;">
                  <el-form-item label="关联关系" style="margin-left: 70px;"></el-form-item>
                  <el-form-item label="字段" style="margin-left: 110px;"></el-form-item>
                  <el-form-item label="条件" style="margin-left: 110px;"></el-form-item>
                  <el-form-item label="值" style="margin-left: 110px;"></el-form-item>
                </div>
                <div v-for="(item, index) in bi.conditions" :key="index" class="select-item">
                  <el-select v-model="item.relation" placeholder="请选择" style="width: 197px">
                    <el-option label="与" value="and"></el-option>
                    <el-option label="或" value="or"></el-option>
                  </el-select>
                  <el-select v-model="item.field" placeholder="请选择" style="width: 197px">
                    <el-option
                      v-for="item in fieldOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <el-select v-model="item.condition" placeholder="请选择" style="width: 197px">
                    <el-option
                      v-for="item in conditionOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                  <el-input v-model="item.value" placeholder="值" style="width:197px"/>

                  <div class="close-btn select-line-icon" @click="removeSelectItem(index)">
                    <i class="el-icon-remove-outline" />
                  </div>

                </div>
                <div style="margin-left: 20px;">
                  <el-button style="padding-bottom: 0" icon="el-icon-circle-plus-outline" type="text" @click="addSelectItem">
                    添加列
                  </el-button>
                </div>
              </div>
              
          </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAnalysis">提交</el-button>
        <!--<el-button @click="cancelUpload">取 消</el-button>-->
      </div>
    </el-dialog>

    <!-- 添加数据源配置对话框 -->
    <el-dialog title="新增数据源" v-if="sourseOpen" :visible.sync="sourseOpen" width="520px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据库类型" prop="databaseType" label-width="100px">
          <!-- <el-input v-model="form.databaseType" placeholder="请输入数据库类型" /> -->
          <el-select v-model="form.databaseType" placeholder="请选择数据库类型">
            <el-option label="MySQL" value="mysql"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="连接名称" prop="linkName" label-width="100px">
          <el-input v-model="form.linkName" placeholder="请输入链接名称" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress" label-width="100px">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port" label-width="100px">
          <el-input v-model="form.port" placeholder="请输入端口号"/>
        </el-form-item>
        <el-form-item label="数据库名称" prop="databaseName" label-width="100px">
          <el-input v-model="form.databaseName" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="100px">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>

import {animateOptions} from '../../animate/animate'
import { dataSourceOptions, dataBaseOptions, statisticsTypeOptions, filterTypeOptions, conditionOptions } from '../../ComponentsConfig'
import { drillDownOptions, getDrillDownOption } from '@/views/tool/datav/components/config/drillDown/drillDown'
import { getAllTable, getAllField, getDistinctOneField } from '@/api/tool/datav/chartDB'
import { listFormsource, addFormsource, updateFormsource, getFormsource } from '@/api/tool/datav/formsource'
import { listSourse, getSourse, addSourse } from '@/api/tool/datav/sourse'
import DrillDownConfig from './drillDown/drillDownConfig'
import { getLinkChart} from "../../util/LinkageChart";
import Databasewebsocket from './chartDB/Databasewebsocket'
import Interactionwebsocket from './chartDB/Interactionwebsocket'

const BIBAR = {
    //图例数据分析结构
    legend: {
      field: '',
      filter: {
        options: [],
        type: '',
        value: ''
      }
    },
    //坐标数据分析结构
    coordinate: {
      field: '',
      filter: {
        options: [],
        type: '',
        value: ''
      }
    },
    //统计数据分析结构
    statistics: {
      field: '',
      //统计类型：计数：count；求和：sum。默认计数
      type: 'count',
      filter: {
        options: [],
        type: '',
        value: ''
      }
    },
    //条件
    conditions: []
};

export default {
  components: {
    DrillDownConfig,
    Databasewebsocket,
    Interactionwebsocket
  },
  props: ["costomData", "drawingList"],
  data() {
    return {
      currentTab: 'field',
      configData: this.costomData,
      animateOptions,
      dataSourceOptions,
      dataBaseOptions,
      statisticsTypeOptions,
      filterTypeOptions,
      conditionOptions,
      drillDownOptions,
      staticDataValue: this.costomData != null ? JSON.stringify(this.costomData.chartOption.staticDataValue) : '',
      arrName: this.costomData != null ? this.costomData.chartOption.arrName : '',
      interfaceUrl: this.costomData.chartOption.interfaceURL != '' ? this.costomData.chartOption.interfaceURL : '',
      requestParameters: this.costomData.chartOption.requestParameters != '' ? this.costomData.chartOption.requestParameters : '',
      database: {
        type: this.costomData.chartOption.database.type,
        ipAdress: this.costomData.chartOption.database.ipAdress,
        port: this.costomData.chartOption.database.port,
        baseName: this.costomData.chartOption.database.baseName,
        username: this.costomData.chartOption.database.username,
        password: this.costomData.chartOption.database.password,
        tableName: this.costomData.chartOption.database.tableName,
        dataSourceId : this.costomData.chartOption.database.dataSourceId,
        fieldName: '',
        executeSql:'',
        chartStucture: {
          legend:[],
          coordinate:[],
          statisticsType: ''
        }
      },
      bi: null,
      //选择目标数据表集合
      tableOptions: [],
      //选择目标字段集合
      fieldOptions: [],
      dbVisble: false,
      loading: true,
      sourseList:[],
       // 表单参数
      form: {},
      // 表单校验
      rules: {
        databaseType: [
          { required: true, message: "数据库类型不能为空", trigger: "blur" }
        ],
        ipAddress: [
          { required: true, message: "ip地址不能为空", trigger: "blur" }
        ],
        port: [
          { required: true, message: "端口号不能为空", trigger: "blur" }
        ],
        databaseName: [
          { required: true, message: "数据库名称不能为空", trigger: "blur" }
        ],
        linkName: [
          { required: true, message: "链接名称不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      },
      //数据库配置表单校验
      dbRules:{
        'legend.filter.value':[
              { required: true, message: "筛选不能为空", trigger: "blur" }
            ],
        'legend.field':[
              { required: true, message: "图例字段不能为空", trigger: "blur" }
            ],
        'coordinate.field':[
              { required: true, message: "坐标字段不能为空", trigger: "blur" }
            ],
        'coordinate.filter.value':[
              { required: true, message: "筛选不能为空", trigger: "blur" }
            ],
        'statistics.field':[
           { required: true, message: "统计字段不能为空", trigger: "blur" }
          ]
      },
      sourseOpen: false,
      chartList: this.drawingList,
      drillDownDialogFlag: false,
      drillBgColor: this.costomData.chartOption.drillDownChartOption != null ? this.costomData.chartOption.drillDownChartOption.drillBgColor : 'rgba(4, 12, 121, 1)',
      formSourceFlag: null,
      formSource: {
        id: this.costomData.chartOption.formSource != undefined ? this.costomData.chartOption.formSource.id : '',
        fileName: this.costomData.chartOption.formSource != undefined ? this.costomData.chartOption.formSource.fileName : '',
        fileUrl: this.costomData.chartOption.formSource != undefined ? this.costomData.chartOption.formSource.fileUrl : '',
        chartType: "line"
      },
      formSourceList: [],
      formQueryParam: {
        chartType: "line"
      },
      fileList: [],
      addFileName: '',
      activeName:['0'],
      fontFamilys:this.fontFamilys,
      lineStyleColor:[{key:"source",name:"源节点颜色"},{key:"target",name:"目标节点颜色"},{key:"customer",name:"自定义颜色"}],
      labelPosition:['top','left','right','bottom','inside','insideLeft','insideRight','insideTop','insideBottom','insideTopLeft','insideBottomLeft','insideTopRight','insideBottomRight'],
      nameLocation:[{key:'start',name:"起点"},{key:'center',name:"中间"},{key:'end',name:"末尾"}],
      orient:[{key:"horizontal",name:"水平"},{key:"vertical",name:"垂直"}],
      nodeAlign:[{key:"justify",name:"双端对齐"},{key:"left",name:"左对齐"},{key:"right",name:"右对齐"}],
      splitLineType:[{key:'solid', name:"实线"},{key:'dashed',name:"短横虚线"},{key:'dotted',name:'点状虚线'}],
      defaultLineShape:[{key:1, name:"直线"},{key:4,name:"折线"},{key:2,name:'样式3'},{key:3, name:"样式4"},{key:5,name:"样式5"},{key:6,name:'样式6'}],
      defaultJunctionPoint:[{key:'border', name:"边缘"},{key:'ltrb',name:"上下左右"},{key:'tb',name:'上下'},{key:'lr',name:'左右'}],
    }
  },
  //页面加载完执行
  mounted() {
    this.getSourseList();
    //获取可联动组件列表
    let chartList = getLinkChart(this.drawingList);
    this.chartList = chartList;

    this.getFormsourceList();
  },
  computed: {
    
  },
  watch: {
    configData: {
      deep: true,
      handler(newVal) {
        // console.log("1=>", newVal);
        this.$emit("costom-change", newVal);
      }
    },
    costomData: {
      deep: true,
      handler(newVal) {
        this.configData = newVal;
        this.staticDataValue = JSON.stringify(newVal.chartOption.staticDataValue);
        this.arrName = newVal.chartOption.arrName;
        this.interfaceUrl = newVal.chartOption.interfaceURL;
        this.requestParameters = newVal.chartOption.requestParameters;
        //分析动态连接数据库结构
        this.database.type = newVal.chartOption.database.type != undefined ? newVal.chartOption.database.type : '';
        this.database.ipAdress = newVal.chartOption.database.ipAdress != undefined ? newVal.chartOption.database.ipAdress : '';
        this.database.port = newVal.chartOption.database.port != undefined ? newVal.chartOption.database.port : '';
        this.database.baseName = newVal.chartOption.database.baseName != undefined ? newVal.chartOption.database.baseName : '';
        this.database.username = newVal.chartOption.database.username != undefined ? newVal.chartOption.database.username : '';
        this.database.password = newVal.chartOption.database.password != undefined ? newVal.chartOption.database.password : '';
        //this.database.tableName = newVal.chartOption.database.tableName != undefined ? newVal.chartOption.database.tableName : '';
        this.database.executeSql = newVal.chartOption.database.executeSql != undefined ? newVal.chartOption.database.executeSql : '';
        if (newVal.chartOption.database.chartStucture != undefined) {
          this.database.chartStucture = newVal.chartOption.database.chartStucture;
        }
        if (newVal.chartOption.bi != undefined && newVal.chartOption.bi != null) {
          this.bi = newVal.chartOption.bi;
        } else {
          this.bi = JSON.parse(JSON.stringify( BIBAR ));
        }
        if (newVal.chartOption.formSource != undefined) {
          this.formSource = newVal.chartOption.formSource;
        } else {
          this.formSource = JSON.parse(JSON.stringify({ id: '', fileName: '', fileUrl: '', chartType: "line" }));
        }
      }
    },
    'costomData.chartOption.database.baseName': {
      handler(val) {
        this.bi = JSON.parse(JSON.stringify( BIBAR ));
        this.$set(this.database, 'tableName', '');
      }
    },
  },
  methods: {
    changeStaticData() {
      //如果是静态数据就给staticDataValue赋值
      if (this.configData.chartOption.isStaticData == true) {
          //this.configData.staticDataValue = JSON.parse(this.staticDataValue);
          this.$set(this.configData.chartOption, 'staticDataValue', JSON.parse(this.staticDataValue));
      } else {
          //this.configData.interfaceURL = this.staticDataValue;
          this.$set(this.configData.chartOption, 'staticDataValue', this.staticDataValue);
      }
    },
    changeInterfaceUrl() {
      this.$set(this.configData.chartOption, 'interfaceURL', this.interfaceUrl);
    },
    changeRequestParameters() {
      this.$set(this.configData.chartOption, 'requestParameters', this.requestParameters);
    },
    DBConn() {
      console.log("bi=>", this.bi);

      //连接数据库
      getAllTable(this.database).then(response => {
          if (response.code == 200) {
              //alert("连接数据库成功");
              this.$message({
                  message: '连接数据库成功',
                  type: 'success'
              });
              console.log(response.data);
              this.tableOptions = response.data;
              this.loading = false;
              this.dbVisble = true;
              this.$set(this.configData.chartOption, 'database', JSON.parse(JSON.stringify( this.database )));
              if(this.database.tableName != ""){
                this.tableSelectChanged(this.database.tableName)
              }
          } else {
              this.$message.error('连接数据库失败');
          }
      });

      //this.dbVisble = true;
      // this.$nextTick(() => {
      //   this.$refs.chartDbFactory.init();
      // })
    },
    tableSelectChanged(value) {

      this.$set(this.database, 'tableName', value);

      //获取数据库下所有字段
      getAllField(this.database).then(response => {
          if (response.code == 200) {
              
              let treeData = [];
              for (const item of response.data) {
                let o = new Object();
                o.id = item.columnName;
                o.label = item.columnName + "( " + item.comment + " )";
                treeData.push(o);
              }
              this.fieldOptions = treeData;
          } else {
              this.$message.error('获取数据库下所有字段失败');
          }
      });
    },
    legendFieldChanged(value) {
      this.$set(this.bi.legend, 'field', value);
      this.database.fieldName = value;
      this.$set(this.bi.legend.filter, 'value', []);
      //获取字段下所有去重分类
      getDistinctOneField(this.database).then(response => {
          console.log(response);
          if (response.code == 200) {
              
              let treeData = [];
              let object = response.data;
              for (const key in object) {
                if (Object.hasOwnProperty.call(object, key)) {
                  const element = object[key];
                  let o = new Object();
                  o.id = key;
                  o.label = element.fieldName;
                  treeData.push(o);
                }
              }
              
              this.$set(this.bi.legend.filter, 'options', treeData);
          } else {
              this.$message.error('获取数据库下所有字段失败');
          }
      });
    },
    coordinateFieldChanged(value) {
      this.$set(this.bi.coordinate, 'field', value);
      this.database.fieldName = value;
      this.$set(this.bi.coordinate.filter, 'value', []);
      //获取字段下所有去重分类
      getDistinctOneField(this.database).then(response => {
          console.log(response);
          if (response.code == 200) {
              
              let treeData = [];
              let object = response.data;
              for (const key in object) {
                if (Object.hasOwnProperty.call(object, key)) {
                  const element = object[key];
                  let o = new Object();
                  o.id = key;
                  o.label = element.fieldName;
                  treeData.push(o);
                }
              }
              
              this.$set(this.bi.coordinate.filter, 'options', treeData);
          } else {
              this.$message.error('获取数据库下所有字段失败');
          }
      });
    },
    addSelectItem(){
      this.bi.conditions.push({
        relation: '',
        field: '',
        condition: '',
        value: ''
      })
    },
    removeSelectItem(index){
      let newCols = this.bi.conditions;
      newCols.splice(index, 1);
    },
    submitAnalysis() {
      // console.log(this.bi);
      //判断是否选择目标表
      if(this.database.tableName == "" || this.database.tableName == undefined ){
        this.$message.error('请选择表');
      }else{
        //校验
      this.$refs["bi"].validate((valid) => {
        if (valid) {
      let selectPart = "select ";
      let wherePart = " where 1=1 ";
      let orderByPart = "";
      let groupByPart = " group by ";

      selectPart = selectPart + this.bi.coordinate.field + " as zbwd, ";
      for (const item of this.bi.legend.filter.options) {
        selectPart = selectPart + this.bi.statistics.type + "(case when " + this.bi.legend.field + "='" + item.label + "' then " + this.bi.statistics.field + " end) as " + item.label + ",";
      }
      selectPart = selectPart.slice(0,-1);
      selectPart = selectPart + " from " + this.database.tableName;

      if(this.bi.coordinate.filter.value !== '') {
        // if(this.bi.coordinate.filter.type === 'standard') {
        //   let object = this.bi.coordinate.filter.value;
        //   let inPart = " and " + this.bi.coordinate.field + " in (";
        //   for (const i of object) {
        //     inPart = inPart + "'" + i + "',";
        //   }
        //   inPart = inPart.slice(0,-1);
        //   inPart = inPart + ")";
        //   wherePart = wherePart + inPart;
        // } else if(this.bi.coordinate.filter.type === 'range') {

        // }

        let object = this.bi.coordinate.filter.value;
        let inPart = " and " + this.bi.coordinate.field + " in (";
        for (const i of object) {
          inPart = inPart + "'" + i + "',";
        }
        inPart = inPart.slice(0,-1);
        inPart = inPart + ")";
        wherePart = wherePart + inPart;

      }

      // 判断筛选条件是否为空
      if (this.bi.conditions) {
        for (const obj of this.bi.conditions) {
          //校验筛选条件
          if(obj.condition == "" || obj.field == "" || obj.relation == ""){
            this.$message.error("请选择筛选条件")
            return false
          }
          //如果是空或null的条件不用拼接值字段
          else if (obj.condition == "is null" || obj.condition == "is not null" || obj.condition == '= ""' || obj.condition == '!= ""' ){
              wherePart = wherePart + ' '+ obj.relation+' ' + obj.field + " " + obj.condition  
          }
          //如果是包含关系，先将可能输入的中文逗号换成英文逗号，再转成数组拼成分别用单引号包起来的字符串
          else if(obj.condition == "in" || obj.condition == "not in"){

            let valueArr = (obj.value.replace("，",",")).split(",");
            let linkResult = '';
            valueArr.forEach(element => {
              linkResult += "'" + element + "',";
            });
            
            linkResult = linkResult.slice(0,linkResult.length-1)

            wherePart = wherePart + ' '+ obj.relation+' ' + obj.field +' ' + obj.condition + "(" + linkResult + ")"
          }
          //其他关系直接拼接
          else{
              wherePart = wherePart + ' '+ obj.relation+' ' + obj.field+' ' + obj.condition + "'" + obj.value + "'"
          }
          
        }
      }
      
      groupByPart = groupByPart + this.bi.coordinate.field;

      let executeSql = selectPart + wherePart + groupByPart + orderByPart;

      //console.log(executeSql);

      this.$set(this.database, 'executeSql', executeSql);

      this.database.chartStucture.legend = this.bi.legend.filter.value;
      this.database.chartStucture.coordinate = this.bi.coordinate.filter.value;
      this.database.chartStucture.statisticsType = this.bi.statistics.type;

      this.$set(this.configData.chartOption, 'database', JSON.parse(JSON.stringify( this.database )));
      this.$set(this.configData.chartOption, 'bi', JSON.parse(JSON.stringify( this.bi )));
      this.dbVisble = false;
        }})}
    },
    //获取数据源列表
    getSourseList(){
        listSourse().then((response) => {      
          this.sourseList = response.rows;
        });
    },
    //连接数据库
    linkDB(){
      //必须选择数据源
      if(this.database.dataSourceId == ''){
       
       this.$message.error('请选择数据源');
       return false;
      
      }else{
        this.loading = true;
        getSourse(this.database.dataSourceId).then((response) => {

          //重新赋值
          this.database.type = response.data.databaseType;
          this.database.ipAdress = response.data.ipAddress ;
          this.database.port = response.data.port;
          this.database.baseName = response.data.databaseName;
          this.database.username = response.data.username;
          this.database.password = response.data.password;
          
          if (response.code == 200) {
      
            this.DBConn()
          }else{
            this.$message.error('连接数据库失败');
          }
                   
        });
      }
      
    },
    addSourse(){
       this.reset();
       this.sourseOpen = true;
    },
     // 取消按钮
    cancel() {
      this.sourseOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.form = {
        id: undefined,
        databaseType: undefined,
        ipAddress: undefined,
        port: undefined,
        databaseName: undefined,
        linkName: undefined,
        username: undefined,
        password: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
            addSourse(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.sourseOpen = false;
                this.getSourseList();
              } else {
                this.msgError(response.msg);
              }
            });
          
        }
      });
    },
    changeArrName(){
      this.$set(this.configData.chartOption, 'arrName', this.arrName);
    },
    bindCharts(val){
       this.$set(this.configData.chartOption, 'bindList', val);
    },
    isLinkChange() {
      if (this.configData.chartOption.isLink == true) {
        this.$set(this.configData.chartOption, 'isDrillDown', false);
        //this.configData.chartOption.isDrillDown == false;
      }
    },
    isDrillDownChange() {
      if (this.configData.chartOption.isDrillDown == true) {
        this.$set(this.configData.chartOption, 'isLink', false);
        //this.configData.chartOption.isLink == false;
      }
    },
    drillDownChartChange(value) {
      const chartOption = getDrillDownOption(value, this.configData.chartOption.theme, this.configData.chartOption.bindingDiv);
      if(chartOption != null){
        chartOption.x = -1;
        chartOption.y = -1;
        chartOption.width = 900;
        chartOption.height = 600;

      }          
      this.$set(this.configData.chartOption, 'drillDownChartOption', chartOption);
      this.$set(this.configData.chartOption.drillDownChartOption, 'drillBgColor', this.drillBgColor);
    },
    drillDownColorChange(){

      if(this.configData.chartOption.drillDownChartOption != null){
        this.$set(this.configData.chartOption.drillDownChartOption, 'drillBgColor', this.drillBgColor);
      } 
    },
    DrillDownClick() {
      if (this.configData.chartOption.drillDownChartType == undefined || this.configData.chartOption.drillDownChartType == null) {
        this.$notify({
          title: '警告',
          message: '请选择关联的下钻组件',
          type: 'warning'
        });
        return false;
      }
      this.drillDownDialogFlag = true;
    },
    //获取表格数据下拉框
    getFormsourceList() {
      listFormsource(this.formQueryParam).then((response) => {
        this.formSourceList = response.rows;
      });
    },
    formChange(option) {
      getFormsource(option).then(response => {
        if (response.code == 200) {
          this.formSource.id = response.data.id;
          this.formSource.fileName = response.data.fileName;
          this.formSource.fileUrl = response.data.fileUrl;
          this.$set(this.configData.chartOption, 'formSource', JSON.parse(JSON.stringify(this.formSource)));
        }
      })
    },
    updateClick() {
      this.formSourceFlag = 'update';
    },
    addClick() {
      this.formSourceFlag = 'add';
    },
    //自定义上传,重写文件上传方法,覆盖原有的上传方法，将上传的文件依次添加到fileList数组中
    httpRequest(option) {
      this.fileList.push(option);
      this.msgSuccess("成功上传至浏览器缓存");
    },
    // 上传预处理
    beforeUpload(file) {
      const Xls = file.name.split('.');
      if (Xls[1] === 'xls' || Xls[1] === 'xlsx') {
        return file;
      } else {
        this.$message.error('请上传excel格式的文件!')
        return false;
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleRemove(file, fileList) {
      this.fileList = [];
    },
    formCancel() {
      this.formSourceFlag = null;
      this.fileList = [];
      this.$refs.upload.clearFiles()
    },
    formSubmit() {
      if (this.fileList.length == 0) {
        this.$message({
          message: '请上传文件在进行提交！',
          type: 'warning'
        });
        return false;
      }
      // 使用form表单的数据格式
      let paramsData = new FormData()
      // 将上传文件数组依次添加到参数paramsData中
      this.fileList.forEach((it, index) => {
        //paramsData.append(`files[${index}]`, it.file)
        paramsData.append('file', it.file); // 因为要上传多个文件，所以需要遍历一下才行
      });
      paramsData.append('chartType', this.formSource.chartType)
      // 将表单数据添加到参数paramsData中
      if (this.formSourceFlag == 'update') {
        paramsData.append('id', this.formSource.id)
        paramsData.append('fileName', this.formSource.fileName)
        paramsData.append('fileUrl', this.formSource.fileUrl)
        updateFormsource(paramsData).then(response => {
          //  console.log(response);
          if (response.code == 200) {
            this.formSourceFlag = null;
            this.fileList = [];
            this.$refs.upload.clearFiles()
            this.msgSuccess("更新成功");
            //this.getFormsourceList();
            this.formSource.id = response.data.id;
            this.formSource.fileName = response.data.fileName;
            this.formSource.fileUrl = response.data.fileUrl;
            this.$set(this.configData.chartOption, 'formSource', this.formSource);
          }
        });
      } else if (this.formSourceFlag == 'add') {
        paramsData.append('fileName', this.addFileName)
        addFormsource(paramsData).then(response => {
          //  console.log(response);
          if (response.code == 200) {
            this.addFileName = '';
            this.formSourceFlag = null;
            this.fileList = [];
            this.$refs.upload.clearFiles()
            this.getFormsourceList();
            this.msgSuccess("新增成功");
            this.formSource.id = response.data.id;
            this.formSource.fileName = response.data.fileName;
            this.formSource.fileUrl = response.data.fileUrl;
            this.$set(this.configData.chartOption, 'formSource', this.formSource);
          }
        });
      }

    },
    getInterfaceKey(val){
      this.$set(this.configData.chartOption, 'interfaceKey', val);
    },
    getRemote(val){
      this.$set(this.configData.chartOption, 'remote', val);
    }
  }
}
</script>


<style lang="scss" scoped>
/deep/ .center-tabs .el-tabs__item {
    width: 25%;
    text-align: center;
}

.select-item {
  display: flex;
  border: 1px dashed #fff;
  box-sizing: border-box;
  & .close-btn {
    cursor: pointer;
    color: #f56c6c;
  }
  & .el-input + .el-input {
    margin-left: 4px;
  }
}

.select-item + .select-item {
  margin-top: 4px;
}

.select-item.sortable-chosen {
  border: 1px dashed #409eff;
}

.select-line-icon {
  line-height: 32px;
  font-size: 22px;
  padding: 0 4px;
  color: #777;
}

.screen>:first-child{
  margin-top:37px
}

/**  滚动条凹槽的颜色，还可以设置边框属性  **/
::-webkit-scrollbar-track-piece { 
  background-color:#f8f8f8; 
  border-radius: 10px;
}

/** 滚动条的宽度  **/
::-webkit-scrollbar {
  width:9px;
  height:9px; 
}

/** 滚动条的设置  **/
::-webkit-scrollbar-thumb {
  background-color:#dddddd;
  background-clip:padding-box;
  min-height:28px; 
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  background-color:#bbb; 
}
/deep/ .el-upload-dragger {
    background-color: #fff;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    box-sizing: border-box;
    width: 225px;
    height: 180px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
</style>